//
//  MapSearchVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/10/25.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "MapSearchVC.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "ListCell.h"
#import "psonCell.h"
#import "MBProgressHUD.h"
#import "YYmapDatamodel.h"
#import "YYmapStationDataModel.h"
#import "MJRefresh.h"
/*
#import "NothingDataView.h"
#import "JoinFaluterView.h"
#import "FallLineView.h"
#import "ServerUnusualView.h"*/

@interface MapSearchVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate/*,NothingViewDelegate,JoinFalutDelegate,FallLineDelegate,ServerUnsualDelegate*/>
{
    UITextField *_searchTF;
    UIButton *_btn1;
    UIButton *_btn2;
    UIButton *_btn3;
    NSInteger tag;
    NSArray *_result;
    NSDictionary *_dispalyDic;//反向传值
    UIView *_bottomLine1;
    UIView *_bottomLine2;
    NSString *_url;
    UIView *_failView;
    NSDictionary *_paramet;
    NSInteger pageNum;
    NSString *_keyword;
    /*
     NothingDataView *_nothing;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
     */
}
@property (strong, nonatomic) UISearchController *searchController;
@property (nonatomic,strong)UITableView *tableview;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,strong)NSMutableArray *psonArr;
@property (nonatomic,strong)NSMutableArray *companyArr;
@property (nonatomic,strong)NSMutableArray *stationArr;
@end

@implementation MapSearchVC
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.tableview.mj_header beginRefreshing];
}
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"定位查询列表";
    self.view.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;

    _keyword = @"";
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *delegate = app.delegate;
    self.userId = delegate.userId;
    _dataSource = [[NSMutableArray alloc]init];
    tag = 1001;
    [self initTableView];
        _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [_dataSource removeAllObjects];
            pageNum = 0;
            _paramet = @{@"userId":[NSString stringWithFormat:@"%ld",self.userId],@"pageNum":[NSString stringWithFormat:@"%ld",pageNum],@"keyword":_keyword};
            //NSSLog(@"%d",_keyword.length);
            if (_keyword.length<1) {
                
                [self load];
                
            }else{
                
                [self networking];
            }
            
        }];
        _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            

            pageNum = pageNum + 1;
            _paramet = @{@"userId":[NSString stringWithFormat:@"%ld",self.userId],@"pageNum":[NSString stringWithFormat:@"%ld",pageNum],@"keyword":_keyword};
            if (_keyword.length<1) {
                
                [self load];
                
            }else{
                
                [self networking];
            }
        }];
   

 
}
/**
 *  停止刷新
 */
-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
}
- (void)initTableView{
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.tableFooterView = [[UIView alloc]init];
    _tableview.backgroundColor = [UIColor clearColor];
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 80)];
    headerView.backgroundColor = [UIColor whiteColor];
    UISearchBar *bar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 5, kSCREEN_WIDTH, 40)];
    bar.showsCancelButton = YES;
    bar.delegate = self;
    bar.placeholder = @"搜索框";
    [headerView addSubview:bar];
    
    UIView *fgline = [[UIView alloc]initWithFrame:CGRectMake(0, 45, kSCREEN_WIDTH, 1)];
    fgline.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [headerView addSubview:fgline];
    _btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btn1 setTitle:@"人     员" forState:UIControlStateNormal];
    [_btn1 setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];

    [_btn1 addTarget:self action:@selector(SearchTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    _btn1.tag = 1001;
    _btn1.selected = YES;
    [headerView addSubview:_btn1];
    [_btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fgline.mas_bottom).offset(2);
        make.left.equalTo(headerView).offset(-1);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/2, 30));
    }];
    _bottomLine1 = [[UIView alloc]init];
    _bottomLine1.backgroundColor = UIColorFromRGB(0x0093d5);
    [headerView addSubview:_bottomLine1];
    [_bottomLine1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView).offset(0);
        make.top.equalTo(_btn1.mas_bottom).offset(0);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/2-1, 2));
    }];
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = UIColorFromRGB(0x4d4d4d);
    [headerView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(headerView);
        make.top.equalTo(fgline.mas_bottom).offset(5);
        make.size.mas_equalTo(CGSizeMake(1, 20));
    }];
    _btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btn2 setTitle:@"站     点" forState:UIControlStateNormal];
    [_btn2 setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];

    [_btn2 addTarget:self action:@selector(SearchTypeClick:) forControlEvents:UIControlEventTouchUpInside];
    _btn2.tag = 1002;
    [headerView addSubview:_btn2];
    [_btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fgline.mas_bottom).offset(2);
        make.left.equalTo(line.mas_right).offset(0);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/2, 30));
    }];
    _bottomLine2 = [[UIView alloc]init];
    _bottomLine2.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [headerView addSubview:_bottomLine2];
    [_bottomLine2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headerView).offset(0);
        make.top.equalTo(_btn2.mas_bottom).offset(0);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/2-1, 2));
    }];
    _tableview.tableHeaderView = headerView;
    [self.view addSubview:_tableview];
}
- (void)load{
    
    if (tag == 1001) {
        _url = K_XsPsonURL;
    }else{
        _url = K_MapStaionListURL;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:_url parameters:_paramet progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //NSSLog(@"%@",dic);
        if (tag == 1001) {
            
            YYmapDatamodel *datamodel = [[YYmapDatamodel alloc]initWithDictionary:dic[@"data"] error:nil];
            for (YYmapPsonListModel *model in datamodel.beanList) {
                
                [_dataSource addObject:model];
            }
            
        }else{
            YYmapStationDataModel *datamodel = [[YYmapStationDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
            for (YYstationListModel *model in datamodel.beanList) {
                [_dataSource addObject:model];
            }
            
        }

        if (_dataSource.count == 0) {
        
            self.tableview.scrollEnabled = NO;

            _failView = [[UIView alloc]initWithFrame:CGRectMake(0, 155, kSCREEN_WIDTH, kSCREEN_HEIGHT-94)];
            _failView.backgroundColor = UIColorFromRGB(0xf0f0f0);
            UIImageView *imageViewP = [[UIImageView alloc]initWithFrame:CGRectMake((kSCREEN_WIDTH-150)/2, 20, 150, 293)];
            imageViewP.image = [UIImage imageNamed:@"img01"];
            UILabel *errorLab = [[UILabel alloc]initWithFrame:CGRectMake((kSCREEN_WIDTH-80)/2, CGRectGetMaxY(imageViewP.frame)+5, 80, 21)];
            errorLab.text = @"没有数据!";
            errorLab.textColor = UIColorFromRGB(0x4d4d4d);
            [_failView addSubview:errorLab];
            UIImageView *errorImage = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(errorLab.frame)-26, CGRectGetMinY(errorLab.frame), 21, 21)];
            errorImage.image = [UIImage imageNamed:@"abnormal_icon"];
            [_failView addSubview:errorImage];
            [_failView addSubview:imageViewP];
            [self.view addSubview:_failView];
        }else{
            
            self.tableview.scrollEnabled = YES;
            [_failView removeFromSuperview];
        }
            [self.tableview reloadData];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self endRefresh];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500 || status == 0) {
            [self showAlert:@"温馨提示" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }

    }];

}
- (void)SearchTypeClick:(UIButton *)sender{

    tag = sender.tag;
    [_dataSource removeAllObjects];
    if (sender.tag == 1001) {
        [_btn1 setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];
        [_btn2 setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        _bottomLine1.backgroundColor = UIColorFromRGB(0x0093d5);
        _bottomLine2.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _keyword = @"";
        [_failView removeFromSuperview];
        [self.tableview.mj_header beginRefreshing];

    }else if (sender.tag == 1002){
        [_btn1 setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        [_btn2 setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];
        _bottomLine2.backgroundColor = UIColorFromRGB(0x0093d5);
        _bottomLine1.backgroundColor = UIColorFromRGB(0xf0f0f0);
        [_failView removeFromSuperview];
        _keyword = @"";
        [self.tableview.mj_header beginRefreshing];

    }

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 44.0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tag == 1001) {
        psonCell *cell = [[psonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

            
            YYmapPsonListModel *model = _dataSource[indexPath.row];
            [cell fillCellWithModel:model];
        
        return cell;
    }else{
        ListCell *cell = [[ListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

           YYstationListModel *model = _dataSource[indexPath.row];
            [cell fillCellWithModel:model];
        
        return cell;
    }

    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
 //2 人员 1分公司 0 自己 3 站点
    if (_searchController.isActive) {
        if (tag == 1001) {
            pson *model = _result[indexPath.row];
            _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                            @"longitude":[NSString stringWithFormat:@"%f",model.lnt],
                            @"phone":model.phone,
                            @"title":model.name,
                            @"subtitle":model.opCenName,
                            @"post":model.post,
                            @"state":@2};
            [self.Delegate displayData:_dispalyDic];
        }else if (tag == 1002){
            MapStation *model = _result[indexPath.row];
            _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                            @"longitude":[NSString stringWithFormat:@"%f",model.lnt],
                            @"phone":model.phone,
                            @"title":model.name,
                            @"subtitle":model.address,
                            @"pson":model.pson,
                            @"opcenter":model.opCenName,
                            @"state":@3};
            [self.Delegate displayData:_dispalyDic];
        }else{
            BranchOfcList *model = _result[indexPath.row];
            _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                            @"longitude":[NSString stringWithFormat:@"%f",model.lnt],
                            @"title":model.branchOfcName,
                            @"subtitle":model.phone,
                            @"pson":model.pson,
                            @"phone":@"",
                            @"state":@1
                            };
            [self.Delegate displayData:_dispalyDic];
        }
    }else{
        if (tag == 1001) {
            pson *model = _dataSource[indexPath.row];
            _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                            @"longitude":[NSString stringWithFormat:@"%f",model.lnt],
                            @"phone":model.phone,
                            @"title":model.name,
                            @"subtitle":@"",
                            @"opcenter":model.opCenName,
                            @"stationNum":[NSString stringWithFormat:@"%ld",model.stationNum],
                            @"post":model.post,
                            @"state":@2};
            [self.Delegate displayData:_dispalyDic];
        }else if (tag == 1002){
            MapStation *model = _dataSource[indexPath.row];
            _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                            @"longitude":[NSString stringWithFormat:@"%f",model.lnt],
                            @"phone":model.phone,
                            @"title":model.name,
                            @"subtitle":@"",
                            @"pson":model.pson,
                            @"opcenter":model.opCenName,
                            @"adress":model.address,
                            @"state":@3};
            [self.Delegate displayData:_dispalyDic];
        }else{
            BranchOfcList *model = _dataSource[indexPath.row];
            _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                            @"longitude":[NSString stringWithFormat:@"%f",model.lnt],                            @"title":model.branchOfcName,
                            @"subtitle":model.address,
                            @"pson":model.pson,
                            @"phone":model.phone,
                            @"state":@1
                            };
            [self.Delegate displayData:_dispalyDic];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
*/
    if (tag==1001) {
       YYmapPsonListModel *model = _dataSource[indexPath.row];
    _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                        @"longitude":[NSString stringWithFormat:@"%f",model.lnt],
                        @"phone":model.phone,
                        @"title":model.username,
                        @"subtitle":model.opCenName,
                        @"post":model.post,
                        @"stationNum":[NSString stringWithFormat:@"%ld",model.stationNum],
                        @"adress":model.address,
                        @"lastTime":model.locationTime,
                        @"state":@2};
        [self.Delegate displayData:_dispalyDic];
    }else{
        YYstationListModel *model = _dataSource[indexPath.row];
        _dispalyDic = @{@"latitude":[NSString stringWithFormat:@"%f",model.lat],
                        @"longitude":[NSString stringWithFormat:@"%f",model.lnt],
                        @"phone":model.phone,
                        @"title":model.stationName,
                        @"subtitle":model.address,
                        @"pson":model.principalName,
                        @"opcenter":model.opCenName,
                        @"adress":model.address,
                        @"state":@3};
        [self.Delegate displayData:_dispalyDic];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [_dataSource removeAllObjects];
    [searchBar resignFirstResponder];
    _keyword = searchBar.text;
    _paramet = @{@"userId":[NSString stringWithFormat:@"%ld",self.userId],@"pageNum":[NSString stringWithFormat:@"%ld",pageNum],@"keyword":_keyword};
     [self.tableview.mj_header beginRefreshing];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [_dataSource removeAllObjects];
    [searchBar resignFirstResponder];
    _keyword = @"";

    [self.tableview.mj_header beginRefreshing];

}
- (void)networking{
    if (tag == 1001) {
        _url = K_XsPsonURL;
    }else{
        _url = K_MapStaionListURL;
    }
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:_url parameters:_paramet progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self endRefresh];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (tag == 1001) {
            
            YYmapDatamodel *datamodel = [[YYmapDatamodel alloc]initWithDictionary:dic[@"data"] error:nil];
            for (YYmapPsonListModel *model in datamodel.beanList) {
                
                [_dataSource addObject:model];
            }
            
        }else{
            YYmapStationDataModel *datamodel = [[YYmapStationDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
            for (YYstationListModel *model in datamodel.beanList) {
                [_dataSource addObject:model];
            }
            
        }
        
        if (_dataSource.count == 0) {
            
            self.tableview.scrollEnabled = NO;
            
            _failView = [[UIView alloc]initWithFrame:CGRectMake(0, 155, kSCREEN_WIDTH, kSCREEN_HEIGHT-94)];
            _failView.backgroundColor = UIColorFromRGB(0xf0f0f0);
            UIImageView *imageViewP = [[UIImageView alloc]initWithFrame:CGRectMake((kSCREEN_WIDTH-150)/2, 20, 150, 293)];
            imageViewP.image = [UIImage imageNamed:@"img01"];
            UILabel *errorLab = [[UILabel alloc]initWithFrame:CGRectMake((kSCREEN_WIDTH-80)/2, CGRectGetMaxY(imageViewP.frame)+5, 80, 21)];
            errorLab.text = @"没有数据!";
            errorLab.textColor = UIColorFromRGB(0x4d4d4d);
            [_failView addSubview:errorLab];
            UIImageView *errorImage = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(errorLab.frame)-26, CGRectGetMinY(errorLab.frame), 21, 21)];
            errorImage.image = [UIImage imageNamed:@"abnormal_icon"];
            [_failView addSubview:errorImage];
            [_failView addSubview:imageViewP];
            [self.view addSubview:_failView];
        }else{
            
            self.tableview.scrollEnabled = YES;
            [_failView removeFromSuperview];
        }

        [self.tableview reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self endRefresh];
        /*if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0, 155, kSCREEN_WIDTH, kSCREEN_HEIGHT-94)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"未能连接到服务器。"]){
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 155, kSCREEN_WIDTH, kSCREEN_HEIGHT-94)];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 155, kSCREEN_WIDTH, kSCREEN_HEIGHT-94)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }*/
    }];
}
/*
- (void)NothingRefresh:(UIButton *)sender{
    
    [_nothing removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self.tableview.mj_header beginRefreshing];
}
*/
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end
